package ar.edu.unq.wannaplay.utils;

import java.util.LinkedList;
import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.ListMultipleChoice;

import ar.edu.unq.wannaplay.dtos.EmployeeDTO;

public class AjaxConfirmSwapListButton extends AjaxButton {

    private static final long serialVersionUID = 1L;

    private List<EmployeeDTO> current;

    private ListMultipleChoice<EmployeeDTO> from;

    private ListMultipleChoice<EmployeeDTO> to;

    public AjaxConfirmSwapListButton(final String id, final List<EmployeeDTO> current,
            final ListMultipleChoice<EmployeeDTO> from, final ListMultipleChoice<EmployeeDTO> to) {
        super(id);
        this.current = current;
        this.from = from;
        this.to = to;

    }

    @Override
    protected void onSubmit(final org.apache.wicket.ajax.AjaxRequestTarget target, final Form<?> form) {
        this.update(target, this.getCurrent(), this.getFrom(), this.getTo());
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public void update(final AjaxRequestTarget target, final List<EmployeeDTO> list, final ListMultipleChoice list1,
            final ListMultipleChoice list2) {

        for (EmployeeDTO employee : list) {
            List<EmployeeDTO> choices = this.getChoices(list1);
            if (!list2.getChoices().contains(employee)) {
                list2.getChoices().add(employee);
                choices.remove(employee);
                list1.setChoices(choices);
            }
        }
        target.addComponent(list1);
        target.addComponent(list2);

    }

    private List<EmployeeDTO> getChoices(final ListMultipleChoice<EmployeeDTO> choice) {
        List<EmployeeDTO> choices = new LinkedList<EmployeeDTO>();
        choices.addAll(choice.getChoices());
        return choices;
    }

    public List<EmployeeDTO> getCurrent() {
        return current;
    }

    public ListMultipleChoice<EmployeeDTO> getFrom() {
        return from;
    }

    public ListMultipleChoice<EmployeeDTO> getTo() {
        return to;
    }

    public void setCurrent(final List<EmployeeDTO> current) {
        this.current = current;
    }

    public void setFrom(final ListMultipleChoice<EmployeeDTO> from) {
        this.from = from;
    }

    public void setTo(final ListMultipleChoice<EmployeeDTO> to) {
        this.to = to;
    }
}